package dao.impl;
import dao.IUserDao;
import dao.BaseDao;
import vo.Type;
import vo.Users;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class UserDao extends BaseDao implements IUserDao {
	public Users addUser(Users user){
		Session session=getSession();
		Transaction tx=session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
		return user;
	}
	public void deleteUser(String userNumber){
		Session session=getSession();
		String hql="delete Users where UserNumber=:un";
		Query query=session.createQuery(hql);
		query.setParameter("un",userNumber);
		query.executeUpdate();
		session.close();
	}
	public List getUserByName(String name){
		Session session=getSession();
		String hql="from Users where UserName like :name";
		Query query=session.createQuery(hql);
		query.setParameter("name","%"+ name+"%");
		List users=query.list();
		session.close();
		return users;
	}
	public void UpdateUserPasswd(int id,String passwd){
		Session session=getSession();
		String hql="update Users set UserPasswd=? where UserID=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, passwd);
		query.setParameter(1,id);
		int ret=query.executeUpdate();
		session.close();
	}
	public List getAllUsers(){
		Session session=getSession();
		String hql="from Users";
		Query query=session.createQuery(hql);
		List users=query.list();
		session.close();
		return users;
	}
	public List getUserById(int id){
		Session session=getSession();
		String hql="from Users where UserID=?";
		Query query=session.createQuery(hql);
		query.setParameter(0, id);
		List users=query.list();
		session.close();
		return users;
	}
	public List getUserByUserNumber(String userNumber){
		Session session=getSession();
		String hql="from Users where userNumber=:userNumber";
		Query query=session.createQuery(hql);
		query.setParameter("userNumber", userNumber);
		List users=query.list();
		session.close();
		return users;
	}
	public void update(Users user){
		Session session=getSession();
		Transaction ts=session.beginTransaction();
		Users u=(Users)session.get(Users.class, user.getUserId());
		if(user.getGender()!=null){
			u.setGender(user.getGender());
		}
		if(user.getPayments()!=null){
			u.setTel(user.getTel());
		}
		if(user.getUserName()!=null){
			u.setUserName(user.getUserName());
		}
		if(user.getUserNumber()!=null){
			u.setUserNumber(user.getUserNumber());
		}
		if(user.getUserPasswd()!=null){
			u.setUserPasswd(user.getUserPasswd());
		}
		session.update(u);
		ts.commit();
		session.close();
	}
}
